package util

import (
	"errors"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

// HTTPGet 封装http get请求
//params[0] Query
//params[1] Header
func HTTPGet(url string, Params ...map[string]string) ([]byte, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Println(err)
		return nil, errors.New("new request is fail ")
	}

	if len(Params) > 0 {
		q := req.URL.Query()
		for key, val := range Params[0] {
			q.Add(key, val)
		}
		req.URL.RawQuery = q.Encode()

	}
	if len(Params) > 1 {
		for key, val := range Params[1] {
			req.Header.Add(key, val)
		}
	}
	client := &http.Client{}
	resp, err := client.Do(req)

	if err != nil {
		return nil, err
	}

	return ioutil.ReadAll(resp.Body)
}

func HttpPost(url string, params string) (string, error) {
	data := strings.NewReader(params)
	req, err := http.NewRequest("POST", url, data)
	if err != nil {
		log.Println(err)
		return "", errors.New("new request is fail ")
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)

	result,err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return "", err
	}

	return string(result), nil
}
